package heman.server.controllers;


import heman.server.database.DatabaseController;
import heman.server.entities.Player;
import heman.server.entities.PlayerManager;
import ks.framework.common.Message;
import ks.framework.communicator.Communicator;
import ks.framework.debug.Debug;
import ks.server.interfaces.IProcessServerMessage;

import org.w3c.dom.Document;

import com.sun.management.VMOption.Origin;

/**
 * Handle the login command for users.
 * 
 * @author  Wenlong Liu
 * 
 */
public class LoginController implements IProcessServerMessage {

	public boolean process(Communicator com, Message m) {
		Debug.println ("Observe login by: " + m.getOriginator());
		//We should first check if the player has already logged in
		//Get the player from the database
		Player newPlayer=DatabaseController.getPlayer(m.getOriginator());
		//Player newPlayer=new Player(m.getOriginator());
		if (newPlayer==null) return false;
		
		PlayerManager.getInstance().addPlayer(newPlayer);
		
		 // produce request to go to the client
		StringBuilder sb = new StringBuilder(Message.responseHeader(true, m.id));
        sb.append("<output system='true'><text>");
        sb.append(m.getOriginator()).append(" logged in");
        sb.append("</text></output></response>");
        Document d = Message.construct (sb.toString());
        
        // send to all clients...
        Message r = new Message (d);
        r.setBroadcast();
        
        com.distribute(r);
        
        //Send Player response to every player online
        sb=new StringBuilder(Message.responseHeader(true));
        sb.append("<playerResponse>");
        sb.append(newPlayer.toXMLPlayer());
        sb.append("</playerResponse></response>");
        
        d = Message.construct (sb.toString());
        
        r = new Message (d);
        r.setBroadcast();//Broadcast except the originator
        
        com.distribute(r);
        
        
        return true;
	}
}